package com.zenithmind.common.aspect;

import com.zenithmind.common.annotation.Log;
import com.zenithmind.common.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 操作日志切面
 * 处理@Log注解，记录系统操作日志
 */
@Slf4j
@Aspect
@Component
@Order(3) // 在API访问日志之后执行
public class LogAspect {

    @Around("@annotation(com.zenithmind.common.annotation.Log)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Log logAnnotation = method.getAnnotation(Log.class);
        
        if (logAnnotation != null) {
            // 获取用户信息
            String userId = "unknown";
            String username = "anonymous";
            try {
                userId = UserContext.getUserId();
                username = UserContext.getUsername();
            } catch (Exception e) {
                log.debug("获取用户信息失败", e);
            }
            
            // 获取请求信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
            String ip = request != null ? getIpAddress(request) : "unknown";
            
            // 获取请求参数
            String params = "";
            if (logAnnotation.recordRequestParams()) {
                params = Arrays.toString(point.getArgs());
            }
            
            // 记录操作日志
            log.info("操作日志: 操作={}, 类型={}, 方法={}, 用户ID={}, 用户名={}, IP={}, 参数={}",
                    logAnnotation.description(),
                    logAnnotation.operationType(),
                    point.getSignature().toShortString(),
                    userId,
                    username,
                    ip,
                    params);
        }
        
        // 执行原方法
        Object result = point.proceed();
        
        // 记录响应结果（如果需要）
        if (logAnnotation != null && logAnnotation.recordResponseResult()) {
            log.info("操作响应: 操作={}, 结果={}", logAnnotation.description(), result);
        }
        
        return result;
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String[] headerNames = {
            "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP",
            "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"
        };
        
        for (String headerName : headerNames) {
            String ip = request.getHeader(headerName);
            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                return ip.split(",")[0].trim();
            }
        }
        
        return request.getRemoteAddr();
    }
} 